<template>
  <view class="upload-content">
    <view class="image-list">
      <view class="image-item" v-for="(image, index) in imageList" :key="index">
        <image :src="config.beaeUrl + image" mode="aspectFill" />
        <view class="delete-btn" @click="handleDelete(index)">×</view>
      </view>
      <view class="upload-btn" v-if="!imageList.length || imageList.length < maxCount" @click="handleUpload">
        <image src="/static/index/add.png" mode="aspectFit" />
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref, defineProps, defineEmits, watch } from 'vue'
  import config from '@/config/public.js'
  import { uploadImage, deleteImage } from '@/api/broken.js'


  const props = defineProps({
    // 最大上传数量
    maxCount: {
      type: Number,
      default: 8
    },
    // 已上传的图片列表
    modelValue: {
      type: Array,
      default: () => []
    },
  })

  const emit = defineEmits(['update:modelValue', 'upload-success', 'upload-error', 'delete-success'])

  // 内部维护的图片列表
  const imageList = ref(props.modelValue)

  // 监听外部传入的值变化
  watch(() => props.modelValue, (newVal) => {
    imageList.value = newVal
    // console.log(imageList.value, '--------')
  })

  // 选择并上传图片
  const handleUpload = () => {
    uni.chooseImage({
      count: props.maxCount - imageList.value.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        res.tempFilePaths.forEach(item => {
          uni.uploadFile({
            url: `${config.beaeUrl}/common/upload`,
            filePath: item,
            name: 'file',
            header: {
              Authorization: uni.getStorageSync('token'),
            },
            success: (uploadRes) => {
              const result = JSON.parse(uploadRes.data)
              if (result.code === 200) {
                const newImageList = [...imageList.value, result.fileName]
                imageList.value = newImageList
                emit('update:modelValue', newImageList)
                emit('upload-success', result.fileName)
              } else {
                emit('upload-error', result.msg)
                uni.showToast({
                  title: result.msg,
                  duration: 1500,
                  icon: 'error'
                })
              }
            },
            fail: () => {
              emit('upload-error', '上传失败')
              uni.showToast({
                title: '上传失败',
                duration: 1500,
                icon: 'error'
              })
            }
          })
        })
      },
      fail: () => {
        uni.showToast({
          title: '图片上传失败，请重试！',
          icon: 'none',
          duration: 1500
        })
      }
    })
  }

  // 删除图片
  const handleDelete = (index) => {
    const imageToDelete = imageList.value[index]
    const newImageList = imageList.value.filter((_, i) => i !== index)
    imageList.value = newImageList
    emit('update:modelValue', newImageList)
    emit('delete-success', imageToDelete)

    deleteImage(imageToDelete).then(() => {
      console.log('imageList.value------------')
    })
  }
</script>

<style lang="scss" scoped>
  .upload-content {
    .image-list {
      display: flex;
      flex-wrap: wrap;

      .image-item {
        width: 140rpx;
        height: 140rpx;
        margin: 14rpx;
        position: relative;

        image {
          width: 100%;
          height: 100%;
          border-radius: 8rpx;
        }

        .delete-btn {
          position: absolute;
          top: -16rpx;
          right: -16rpx;
          width: 42rpx;
          height: 42rpx;
          background: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 22rpx;
        }
      }

      .upload-btn {
        width: 140rpx;
        height: 140rpx;
        margin: 14rpx;
        background: #fff;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 2px dashed #ddd;

        image {
          width: 30rpx;
          height: 30rpx;
        }
      }
    }
  }
</style>